import { pageCuesTopic, pageCuesTopicInit } from '@/services/api/api-cues-topic';
import { CloseCircleOutlined, FileTextOutlined, LikeOutlined, ReloadOutlined, StopOutlined } from '@ant-design/icons';
import { LightFilter, ProFormSelect, ProList, ProTable } from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Button, Flex, Input, Space, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableTopicMediaDetailsRecord from './TableTopicMediaDetailsRecord';
import TableTopicMediaDetailsSubmit from './TableTopicMediaDetailsSubmit';
import { parse } from '@/utils/historyUtils';

interface TableTopicMediaProps {
  mode: number;
  loading: boolean;
  industryIds: any[];
  actionRef?: ActionType;
  onRefurbish: () => void;
}

const TableTopicMedia: React.FC<TableTopicMediaProps> = (props) => {
  const userRef = useRef<ActionType>();
  const userRefList = useRef<ActionType>();
  const access = useAccess();
  const [topicId, settopicIdState] = useState()
  useEffect(() => {
    const { topicId } = parse(location.search) as { topicId: string };
    console.log(topicId);
    settopicIdState(topicId);
  }, [])

  useEffect(() => {
    if (props.loading) {
      userRef.current?.reload();
      getCuesTopicCard()
      props.onRefurbish();
    }
  }, [props.loading]);

  /**
   * 行业
   */
  const [queryParam, setQueryParamState] = useState({});
  /**
     * 行业
     */
  const [cardList, setCardListState] = useState([]);

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          key: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined, children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 请求网络
   * @param value
   */
  // const request = async (params = {}) => {
  //   const response = await pageCuesTopic({ pageSize: 10, current: 1, run: 1, mode: 1 });
  //   if (response.code === 0) {
  //     setCardListState(response.data.data)
  //   }
  //   return Promise.resolve({
  //     data: response.data.data,
  //     total: response.data.total,
  //     success: response.code === 0,
  //   });
  // };
  const getCuesTopicCard = async () => {
    const response = await pageCuesTopic({ pageSize: 12, current: 1, mode: props.mode, recordStates: [3], run: 1 });
    if (response.code === 0) {
      setCardListState(response.data.data)
    }
  }
  useEffect(() => {
    getCuesTopicCard()
  }, [])
  /**
 * 请求网络
 * @param value
 */
  const requestTable = async (params = {}) => {
    const response = await pageCuesTopic({ ...params, mode: props.mode, ...queryParam });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  /**
   * 查询单位
   */
  const [queryOrganizations, setQueryOrganizationsState] = useState<any>();

  /**
   * 加载 页面初始化信息
   * @param key
   */
  const loadPageCuesTopicInitData = async () => {
    try {
      const response = await pageCuesTopicInit({ mode: props.mode });
      if (response.code === 0) {
        setQueryOrganizationsState(readyTreeData(response.data.queryOrganizations));
      }
    } catch (error) { }
  };

  useEffect(() => {
    // loadPageCuesTopicInitData();
  }, []);

  const IconText = ({ icon, text }: { icon: any; text: string }) => (
    <span style={{ color: '#1677FF' }}>
      {React.createElement(icon, { style: { marginInlineEnd: 8 } })}
      {text}
    </span>
  );
  const TitleText = ({ title, text }: { title: string; text: any }) => (
    <span style={{ color: '#1677FF' }}>
      {title}：{text}
    </span>
  );
  return (
    <>
      {cardList.length > 0 ? <ProList<CuesTopicData.TopicPage>
        header={false}
        headerTitle={false}
        ghost={true}
        itemCardProps={{
          ghost: false,
        }}
        actionRef={userRefList}
        dataSource={cardList}
        showActions="hover"
        grid={{ gutter: 18, column: 4 }}
        onItem={(record: any) => {
          return {
            onMouseEnter: () => {
              console.log("eeeeeeeeeeeeeeeee");
            },
            onClick: () => {
            },
          };
        }}
        renderItem={(item: CuesTopicData.TopicPage, index: number) => {
          if (item.isRelease === 1) {
            return (
              <TableTopicMediaDetailsSubmit
                topicId={topicId}
                item={item}
                onRefurbish={() => {
                  userRef.current?.reload();
                  getCuesTopicCard()
                  userRefList.current?.reload();
                }}
                triggerMode='card'
                title=''
              />
            );
          } else {
            return (
              <TableTopicMediaDetailsRecord
                topicId={topicId}
                triggerMode={'card'}
                item={item}
                onRefurbish={() => {
                  userRef.current?.reload();
                  getCuesTopicCard()
                  userRefList.current?.reload();
                }}
              />
            );
          }
        }}
        rowKey={'id'}
        toolBarRender={false}

      /> : <></>}

      <ProTable<CuesTopicData.TopicPage>
        columns={[
          {
            title: '选题标题 ',
            key: 'name',
            dataIndex: 'name',
            width: '180px',
            search: false,
            ellipsis: true,
            render: (_, row) => {
              let recordStateName = '';
              let recordStateColor = '';
              let cover = '';
              let recordActions: React.JSX.Element[] | React.ReactNode[] | undefined = [];

              if (row.recordState === 1) {
                cover = 'https://wx4.sinaimg.cn/mw2000/0033ImPzly1hj076fx0z4j60p00p00w502.jpg';
                recordStateName = '申请';
                recordStateColor = '#108ee9';
                recordActions = [
                  <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
                  <IconText icon={StopOutlined} text="撤回" key="list-vertical-star-o" />,
                  // <IconText icon={LikeOutlined} text="发布" key="list-vertical-like-o" />,
                  <IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />,
                ];
              } else if (row.recordState === 2) {
                cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fx3ilj60p00p0wi502.jpg';
                recordStateName = '退回';
                recordStateColor = '#f50';
                recordActions = [
                  <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
                  <IconText icon={FileTextOutlined} text="详情" key="list-vertical-like-o" />,
                ];
              } else if (row.recordState === 3) {
                cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fwx7zj60p00p0tc802.jpg';
                recordStateName = '通过';
                recordStateColor = '#87d068';
                recordActions = [
                  <TitleText
                    title="上报单位"
                    text={row.countSubmitOrganization}
                    key="list-vertical-star-o"
                  />,
                  <TitleText title="报送线索" text={row.countSubmit} key="list-vertical-star-o" />,
                ];
              } else if (row.recordState === 4) {
                cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fwzrfj60p00p0adi02.jpg';
                recordStateName = '废弃';
                recordStateColor = '#FF4D4F';
                recordActions = [<IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />];
              } else {
                cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fx3ilj60p00p0wi502.jpg';
                recordStateName = '撤回';
                recordStateColor = '#FFA500';
                recordActions = [
                  <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
                  <IconText icon={FileTextOutlined} text="详情" key="list-vertical-like-o" />,
                ];
              }
              return (
                <>
                  {row.isLinkage === 1 && <Tag color="orange">{row.linkageType === 1 ? '协助媒体' : row.linkageType === 2 ? '联动部门' : row.linkageType === 3 ? '协助媒体、单位' : '暂无'}</Tag>}
                  <Tag color={recordStateColor}>{recordStateName}</Tag>
                  <Tag color={row.grade === 1 ? '#f50' : row.grade === 2 ? '#ffd591' : '#2db7f5'}>{row.grade === 1 ? '重大' : row.grade === 2 ? '重要' : '一般'}</Tag>
                  <Tag color={row.run === 1 ? 'green' : row.run === 2 ? 'red' : 'orange'}>
                    {row.run === 1 ? '进行中' : row.run === 2 ? '已结束' : '已暂停'}
                  </Tag>
                  {row.showView === 1 && row.isView === 0 ? (
                    <Tag color="red">未阅读</Tag>
                  ) : row.showSubmit === 1 && row.isSubmit === 0 ? (
                    <Tag color="red">未报送</Tag>
                  ) : (
                    <></>
                  )}
                  {/* <a onClick={() => { setFormItemState(row), setTableTitleState(row.name) }}>{row.name}</a> */}
                  <TableTopicMediaDetailsSubmit
                    topicId={topicId}
                    item={row}
                    onRefurbish={() => {
                      userRef.current?.reload();
                      userRefList.current?.reload();
                    }}
                    triggerMode='title'
                    title={row.name}
                  />
                </>
              )
            }
          },
          {
            title: '报送单位',
            dataIndex: 'createdOrganizationAvatar',
            key: 'createdOrganizationAvatar',
            width: '80px',
            valueType: 'avatar',
            render: (dom, row) => (
              <Space>
                <span>{dom}</span>
                {row.createdOrganizationName}
              </Space>
            ),
          },
          // {
          //   title: '选题方向',
          //   dataIndex: 'industryNames',
          //   width: '100px',
          //   key: 'id',
          //   render: (_, row) => {
          //     let industryNames = row?.industryNames;
          //     if (industryNames.length > 3) {
          //       industryNames = industryNames.slice(0, 3);
          //       industryNames.push('...');
          //     }
          //     return <Space size={[0, 8]} wrap>
          //       {industryNames.map((item) => (
          //         <Tag key={item}>{item}</Tag>
          //       ))}
          //     </Space>
          //   },
          // },
          // {
          //   title: '发布媒体',
          //   dataIndex: 'createdOrganizationName',
          //   key: 'createdOrganizationName',
          //   width: '80px',
          //   align: 'center',
          // },
          // {
          //   title: '标签',
          //   dataIndex: 'labelNames',
          //   width: '100px',
          //   key: 'id',
          //   render: (_, row) => {
          //     let labelNames = row?.labelNames;
          //     if (labelNames.length > 3) {
          //       labelNames = labelNames.slice(0, 3);
          //       labelNames.push('...');
          //     }
          //     return <Space size={[0, 8]} wrap>
          //       {labelNames.map((item) => (
          //         <Tag key={item}>{item}</Tag>
          //       ))}
          //     </Space>
          //   },
          // },
          {
            title: '截止时间',
            dataIndex: 'deadlineTime',
            key: 'deadlineTime',
            width: '80px',
            align: 'center',
            valueType: 'dateTime'
          },
          {
            title: '报送线索',
            dataIndex: 'countSubmit',
            key: 'countSubmit',
            width: '50px',
            align: 'center',
            search: false,
          },
          {
            title: '报送单位',
            dataIndex: 'countSubmit',
            key: 'countSubmit',
            width: '50px',
            align: 'center',
            hideInTable: access.线索征集x配置x提供者,
            search: false,
          },
          // {
          //   title: '数据统计',
          //   valueType: 'option',
          //   key: 'option',
          //   width: '120px',
          //   align: 'center',
          //   render: (text, record, _, action) => {
          //     if (record.recordState === 3) {
          //       if (access.线索征集x配置x提供者) {
          //         return <>
          //           <TitleText
          //             key={'title_text_count_submit_organization'}
          //             title="报送线索"
          //             text={record.countSubmit}
          //           /></>
          //       } else {
          //         return <>
          //           <TitleText
          //             key={'title_text_count_submit_organization'}
          //             title="报送单位"
          //             text={record.countSubmitOrganization}
          //           />
          //           <TitleText key={'title_text_count_submit'} title="报送线索" text={record.countSubmit} />
          //         </>
          //       }
          //     } else {
          //       return <>
          //         <Button icon={<FileTextOutlined />}>详情</Button>
          //       </>
          //     }
          //   },
          // },
        ]}
        headerTitle={false}
        ghost={true}
        pagination={{
          defaultPageSize: 9,
          showSizeChanger: false,
        }}
        search={false}
        actionRef={userRef}
        request={requestTable}

        rowKey={'id'}
        toolbar={{
          search: {
            onChange: (e) => {
              setQueryParamState({ ...queryParam, name: e.target.value });
            },
            onSearch: (value) => {
              userRef.current?.reset();
            }
          },
          filter: (
            <LightFilter
              initialValues={{}}
              onValuesChange={(value) => {
                setQueryParamState(value);
                userRef.current?.reset();
              }}
              onFinish={async (values) => console.log(values.sex)}
            >
              <ProFormSelect
                name="recordStates"
                label="状态"
                mode="multiple"
                options={[
                  {
                    label: '申请',
                    value: 1,
                  },
                  {
                    label: '退回',
                    value: 2,
                  },

                  {
                    label: '废弃',
                    value: 4,
                  },
                  {
                    label: '通过',
                    value: 3,
                  },
                ]}
              />
              <ProFormSelect
                name="isLinkage"
                label="联动"
                options={[
                  {
                    label: '是',
                    value: 1,
                  },
                  {
                    label: '否',
                    value: 0,
                  },
                ]}
              />
              {/* <ProFormSelect
                name="industryIds"
                label="行业"
                mode="multiple"
                showSearch
                options={props.industryIds}
              /> */}
            </LightFilter>
          ),
        }}
      />
    </>
  );
};

export default TableTopicMedia;
